package com.lsh.oms.core.email;

import com.lsh.oms.core.enums.RunSystem;
import com.lsh.oms.core.model.email.EmailModel;
import com.lsh.oms.core.service.asynservice.OmsEventBus;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

/**
 * lsh-oms
 *
 * @author panxudong
 * @date 16/9/20
 */
@Component
public class SendEmailService {

    private static Logger logger = LoggerFactory.getLogger(SendEmailService.class);

    @Autowired
    private MailSender mailSender;

    @Value("${run.system}")
    private String runSystem;

    @Value("${email.address}")
    private String receivers;

    private static String EMAIL_NAME = "miaozhuang@lsh123.com";

    /**
     * 邮件发送
     *
     * @param content
     * @param title
     * @param array
     * @return
     */
    public boolean send(String content, String title, String[] array) {
        if (array == null) {
            return false;
       }
        if (StringUtils.isBlank(content)) {
           return false;
       }
       SimpleMailMessage mail = new SimpleMailMessage();

       try {
            mail.setTo(array);
            mail.setFrom(EMAIL_NAME);
            mail.setSubject(title);
            mail.setText(content);
           mailSender.send(mail);
       } catch (Exception e) {
            logger.error("邮件发送失败", e);
           return false;
       }

        return true;
    }


    /**
     * 异步发送邮件
     *
     * @param content 邮件内容
     * @param title   邮件标题
     */
    public void asyncSendEmail(String content, String title) {
        String[] mailreceivers = receivers.split(",");

        this.asyncSendEmail(content, title, mailreceivers);
    }

    /**
     * 异步发送邮件
     *
     * @param content 邮件内容
     * @param title   邮件标题
     */
    public void asyncSendEmail(String content, String title, String[] receivers) {

        title = new StringBuilder().append("[").append(RunSystem.getName(runSystem)).append("]")
                .append("-->").append("[").append(title).append("]").toString();

        OmsEventBus.post(new EmailModel(content, title, receivers));
    }
}
